import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import { ResultData } from "@/api/interface";
import { ResultEnum } from "@/enum/http";
import { LangStore } from "~/stores/modules/lang";

/**
 * pinia 错误使用说明示例
 * https://github.com/vuejs/pinia/discussions/971
 * https://github.com/vuejs/pinia/discussions/664#discussioncomment-1329898
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#single-page-applications
 */
export const config = {
	// 默认地址请求地址，可在 .env 开头文件中修改
	baseURL: import.meta.env.VITE_API_URL as string,
	// 设置超时时间(10s)
	timeout: ResultEnum.TIMEOUT as number,
	// 跨域时候允许携带凭证
	withCredentials: true
};

export abstract  class BaseRequestHttp {
	service: AxiosInstance;
	public constructor(config: AxiosRequestConfig,responseFunc:(response: AxiosResponse,config:any)=>any,asyncErrorFunc:(response: AxiosError)=>Promise<any>) {
		// 实例化axios
		this.service = axios.create(config);

		/**
		 * @description 请求拦截器
		 * 客户端发送请求 -> [请求拦截器] -> 服务器
		 * token校验(JWT) : 接受服务器返回的token,存储到vuex/pinia/本地储存当中
		 */
		this.service.interceptors.request.use(
			(config: AxiosRequestConfig) => {
				console.log(import.meta.env.VITE_API_URL)
				console.log(import.meta.env.VITE_PUBLIC_URL)
				// * 如果当前请求不需要显示 loading,在 api 服务中通过指定的第三个参数: { headers: { noLoading: true } }来控制不显示loading，参见loginApi
				const header: any = {};
				const { transt , getReqHeader} = LangStore();
				const xIp = getReqHeader['x-real-ip'] ? getReqHeader['x-real-ip'] : ''
				console.log(xIp,"asdas")
				header["h-real-ip"] = xIp;
				config.params = transt(config.params,'zh-CN');
				console.log(xIp,"111asdas")
				return { ...config, headers: { ...config.headers, ...header } };
			},
			(error: AxiosError) => {
				return Promise.reject(error);
			}
		);

		/**
		 * @description 响应拦截器
		 *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
		 */
		this.service.interceptors.response.use(
			(response: AxiosResponse) => {
				const lang = response.headers["lang"]
				const { setLang } = LangStore()
				setLang(lang)
				return responseFunc(response,config)
			},
			async (error: AxiosError) => asyncErrorFunc(error)
		);
	}

	// * 常用请求方法封装
	get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.get(url, { params, ..._object });
	}
	post<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.post(url, params, _object);
	}
	put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
		return this.service.put(url, params, _object);
	}
	delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
		return this.service.delete(url, { params, ..._object });
	}
	download(url: string, params?: object, _object = {}): Promise<BlobPart> {
		return this.service.post(url, params, _object);
	}
}
